<template>
  <div class="_wz_cent_main _wz_site">
    <div class="_wz_vehicleMonitoring_cent" style="height: 100%;overflow: hidden;">
      <div class="_wz_vehicleMonitoring_cent_left">
        <Card dis-hover :bordered="true" style="height: 100%;">
          <p slot="title">地图</p>
          <div slot="extra">
            <span style="margin: 0 5px;"><span style="width: 15px;height: 15px;background: #2d8cf0;display: inline-block;border-radius: 50%;margin: 0 5px;"></span>在线车辆</span>
            <span style="margin: 0 5px;"><span style="width: 15px;height: 15px;background: #5c5c5c;display: inline-block;border-radius: 50%;margin: 0 5px;"></span>离线车辆</span>
            <span style="margin: 0 5px;"><span style="width: 15px;height: 15px;background: #ed4014;display: inline-block;border-radius: 50%;margin: 0 5px;"></span>未知车辆</span>
          </div>
          <div class="_wz_vehicleMonitoring_cent_left_map">
            <div class="baidumap" id="_wz_vehicleMonitoring_allmap"></div>
            <div style="min-height:50px;max-height:150px;padding:10px;overflow: auto;border: 1px solid #e6e6e6;margin: 10px 0 0 0;">
              <div>定位车辆：
                <template v-if="vehicleSelected.length > 0">
                  <template v-for="item,index in vehicleSelected">
                    <Tag color="#2d8cf0" closable @on-close="carUncheck" v-if="item.onlineState == 1" :name="index">{{ item.carPlateNo }}</Tag>
                    <Tag color="#5c5c5c" closable @on-close="carUncheck" v-else :name="index">{{ item.carPlateNo }}</Tag>
                  </template>
                </template>
                <template v-else>
                  未选中车辆
                </template>
              </div>
            </div>
          </div>
        </Card>
      </div>
      <div class="_wz_vehicleMonitoring_cent_right">
        <Card dis-hover :bordered="true" style="height: 100%;">
          <p slot="title">
            <!--            车辆列表-->
          </p>
          <div slot="extra">
            定时刷新：
            <i-switch v-model="formDataSearch.timing" :true-value="Number(1)" :false-value="Number(0)" @on-change="singlePointAdd()">
              <span slot="open">开启</span>
              <span slot="close">关闭</span>
            </i-switch>
          </div>
          <Form :model="formDataSearch" label-position="right" inline>
            <FormItem label="">
              <i-input v-model="formDataSearch.carPlateNo" placeholder="请输入车牌号" clearable style="width: 100px;" />
            </FormItem>
            <FormItem>
              <Button type="primary" @click="searchSubmit">搜索</Button>
            </FormItem>
          </Form>
          <div class="_wz_vehicleMonitoring_cent_right_list">
            <dl v-if="tableData.length > 0">
              <dd v-for="item,index in tableData" @click="vehicleSelectedFun(item)">
                <div style="line-height: 30px;margin: 0 0 0 10px;">
                  <div>
                    <template v-if="!!item.vehiclePosition">
                      <img src="../../../assets/b4.png" v-if="item.vehiclePosition.isOnline" style="vertical-align:middle;" :style="{'transform':'rotate('+item.vehiclePosition.direction+'deg)'}" />
                      <img src="../../../assets/b5.png" v-else style="vertical-align:middle;"  :style="{'transform':'rotate('+item.vehiclePosition.direction+'deg)'}" />
                    </template>
                    <img src="../../../assets/b6.png" v-else style="vertical-align:middle;" />

                    <span>{{ item.carPlateNo }}</span>
                  </div>
                  <div style="width:100%;overflow: hidden;text-overflow:ellipsis;white-space: nowrap;">{{item.deptName}}</div>
                </div>
              </dd>
            </dl>
            <div class="_wz_vehicleMonitoring_cent_right_listDiv" v-else>暂无数据</div>
            <Page :total="tableTotal" simple :current="page" @on-change="changePage" :styles="pageStyle" />
          </div>
        </Card>
      </div>
    </div>
    <Spin size="large" fix v-if="spinShow"></Spin>

  </div>
</template>
<script>
import {BmlMarkerClusterer} from 'vue-baidu-map'

export default {
  components: {
    BmlMarkerClusterer
  },
  data() {
    return {
      vehicleSelected: [],//车辆选中
      spinShow: false,//本页加载
      active: '',
      startTime: {},//轨迹开始时间
      endTime: {},//轨迹结束时间
      formDataSearch: {
        timing: 0
      },
      tableData: [],//分页数据
      map: null,//地图
      markers: [],//地图标记物数组
      BMapWz: [],//地图一屏展示使用
      timingCoordinates: null,//定时刷新地图坐标
      markerClusterer: null,//点距合  清除的时候使用
      pageStyle: {
        textAlign: "center"
      },
      page: 1,//当前页码
      limit: 10,//当前页码
      tableTotal: 0,//总条数
    }
  },
  beforeCreate() {//beforeCreate创建前状态

  },
  created() {//created创建完毕状态

  },
  beforeMount() {//beforeMount挂载前状态   DOM 元素然后塞入页面的过程

  },
  mounted() {//mounted 挂载结束状态
    let that = this;

    that.tableLoadData();
    that.mapLoad();
  },
  methods: {//执行的方法

    //取消选中
    carUncheck(event, index) {
      var that = this;
      this.vehicleSelected.splice(index, 1);
      this.singlePointAdd(true);
    },
    //车辆选中
    vehicleSelectedFun(obj) {
      var that = this;
      if(obj.onlineState == -1){
        that.$Message.warning("无法获取未知车辆定位，不可点击！")
        return false;
      }
      var data = JSON.parse(JSON.stringify(that.vehicleSelected));
      var selectData = JSON.parse(JSON.stringify(obj));
      // var selectData = {carPlateNo: obj.carPlateNo, carPlateColor: obj.carPlateColor, uuid: obj.uuid}
      if (JSON.stringify(data).indexOf(JSON.stringify(selectData)) != -1) {
        that.$Message.warning("该车辆已存在！")
        return false;
      } else {
        if (data.length > 9) {
          that.$Message.warning('最多可勾选10辆车辆定位');
          return false;
        } else {
          data.push(selectData)
        }
      }
      that.vehicleSelected = data;

    },
    //地图加载
    mapLoad() {
      let that = this;
      that.map = new BMap.Map("_wz_vehicleMonitoring_allmap");    // 创建Map实例
      that.map.centerAndZoom(new BMap.Point(105.058886,36.028623), 5);  // 初始化地图,设置中心点坐标和地图级别
      //添加地图类型控件
      that.map.addControl(new BMap.MapTypeControl({
        mapTypes: [
          BMAP_NORMAL_MAP,
          BMAP_HYBRID_MAP
        ]
      }));
      that.map.setCurrentCity("邢台");          // 设置地图显示的城市 此项是必须设置的
      that.map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
      // 左上角，添加比例尺
      let top_left_control = new BMap.ScaleControl({anchor: BMAP_ANCHOR_TOP_LEFT});
      that.map.addControl(top_left_control);
      //左上角，添加默认缩放平移控件
      let top_left_navigation = new BMap.NavigationControl();
      that.map.addControl(top_left_navigation);
    },
    //加载表格数据
    tableLoadData() {
      let that = this;
      let formDataSearch = JSON.parse(JSON.stringify(that.formDataSearch));//获取表单数据  和分页 条数
      formDataSearch.page = that.page;
      formDataSearch.limit = that.limit;
      formDataSearch.internetState = 1;
      // that.spinShow = true;
      that.axios.post(that.apiUrl.webApi + "/core/vehicle/coreVehiclePageList", formDataSearch).then(res => {
        // that.spinShow = false;
        if (!!res) {
          that.tableData = res.data.data;
          that.tableTotal = res.data.count;
          // that.vehicleSelected = [];//搜索 删除选中数据
          // that.singlePointAdd();//发起地图渲染业务
        }
      }).catch(err => {
        console.log('失败', err);
      })
    },
    //搜索
    searchSubmit() {
      // let routeData = this.$router.resolve({name: "positioningTrajectory",});
      // window.open(routeData.href, '_blank');
      // return ;
      this.page = 1;
      this.searchCriteria = JSON.parse(JSON.stringify(this.formDataSearch));
      this.tableLoadData();
    },
    changePage(page) {//返回第几页
      this.page = page;//设置当前页数
      this.tableLoadData();
    },
    //单点添加
    singlePointAdd(type) {
      let that = this;
      //清除定时
      clearInterval(that.timingCoordinates)

      if (that.vehicleSelected.length > 0) {//有选中数据
        that.mapRendering(type);
      }else{
        //清除地图
        that.removeOverlay();
      }
    },
    //地图请求坐标渲染
    mapRendering(type) {//type true  车辆选中  可以执行缩放    else => 不执行缩放
      /*
      * 发起请求
      * 结果回来后 判断是否开启 定时
      * 开启定时 在执行定时回调
      * 渲染地图
      * 开启定时 不缩放地图
      * */
      let that = this;
      var data = [];
      that.vehicleSelected.forEach(function (k, i) {
        data.push(k.carPlateNo + '_' + k.carPlateColor)
      })
      that.axios.post(that.apiUrl.webApi + "/position/positionList", {vehicles: data}).then(res => {
        // that.spinShow = false;
        if (!!res) {
          //清除地图
          that.removeOverlay();
          if (!!that.formDataSearch.timing) {//开启定时
            that.timingCoordinates = setTimeout(function () {// 只调用一次
              that.singlePointAdd();
            }, 3000);
          }

          that.BMapWz = [];
          that.markers = [];
          if (!!res.data.data) {
            res.data.data.forEach(function (k, i) {
              if (!!k.lonX && k.lonX.length > 0 && k.lonX != null && !!k.latY && k.latY.length > 0 && k.latY != null) {
                let myIcon;
                if(k.isOnline){//在线
                  myIcon = new BMap.Icon("../../static/img/vehicleImg/b4.png", new BMap.Size(25, 25));
                }else{//离线
                  myIcon = new BMap.Icon("../../static/img/vehicleImg/b5.png", new BMap.Size(25, 25));
                }

                let marker = new BMap.Marker(new BMap.Point(k.lonX, k.latY), {
                  icon: myIcon,
                  title: k.carPlateNo
                });  // 创建标注
                marker.setRotation(k.direction);
                that.map.addOverlay(marker);            //增加点




                var data = k;
                var html = '<div style=\'background:#FFFFFF;color:#000000;font-weight:normal;line-height: 25px;border-top:solid  1px #ccc\'>' +
                  '<div>行驶速度：' + data.vec1 + ' / ' + data.vec2 + '</div>' +
                  '<div>总里程数：' + data.vec3 + '公里</div>' +
                  '<div>行驶状态： ' + ((data.state >> 0 & 1) ? '启动' : '熄火') +((data.state >> 1 & 1) ? ' - 定位' : ' - 未定位') +'</div>' +
                  '<div>报警状态： ' + ((data.alarm >> 1 & 1) ? '超速报警' : "无超速") + ((data.alarm >> 2 & 1) ? '-疲劳报警' : " - 无疲劳") +'</div>'+
                  '<div>定位时间：' + data.dateTime + '</div>'+
                  '<div style="word-break:break-all;">' + data.location + '</div>'+
                  '</div>';
                var point = new BMap.Point(k.lonX, k.latY);

                var opts = {
                  title : data.carPlateNo , // 信息窗口标题
                }
                var infoWindow = new BMap.InfoWindow(html, opts);  // 创建信息窗口对象
                marker.addEventListener("click", function(){
                  that.map.openInfoWindow(infoWindow, point); //开启信息窗口
                });


                //
                // var BaiMakerLabel = new BMap.Label(html, {offset: new BMap.Size(22, -3)});
                // BaiMakerLabel.setStyle({border: 'none', padding: '3px 5px', background: 'none'});
                // marker.setLabel(BaiMakerLabel);






                // that.map.centerAndZoom(new BMap.Point(data.lonX, data.latY), 8);  // 初始化地图,设置中心点坐标和地图级别
                // that.markers.push(marker);
                that.BMapWz.push(new BMap.Point(k.lonX, k.latY));//一屏显示用
              }
            })
          }

          if (!!type) {
            // //最简单的用法，生成一个marker数组，然后调用markerClusterer类即可。
            that.markerClusterer = new BMapLib.MarkerClusterer(that.map, {markers: that.markers});
            // //坐标自动展示所有的坐标  一平显示
            that.map.setViewport(that.BMapWz);
          }
        }
      }).catch(err => {
        console.log('失败', err);
      })


    },
    //清除地图
    removeOverlay() {
      this.map.clearOverlays();
      if (!!this.markerClusterer) {
        this.markerClusterer.clearMarkers();
        this.markerClusterer = null;
      }
    },
  },
  watch: {//监听
    //车辆选择
    vehicleSelected(news, old) {
      this.singlePointAdd(true);
    },

  },
  props: {//接收来自父组件的数据

  },
  beforeUpdate() {//beforeUpdate 更新前状态

  },
  updated() {//updated 更新完成状态

  },
  beforeDestroy() {//beforeDestroy 销毁前状态

  },
  destroyed() {//destroyed 销毁完成状态
    clearInterval(this.timingCoordinates)

  }
}
</script>
<style lang="less">
._wz_site {
  display: flex;
  flex-direction: column;

  .ivu-input-wrapper {
    min-width: 10px;
  }


  .baidumap {
    height: 100%;
    width: 100%;
  }


  ._wz_vehicleMonitoring_cent {
    width: 100%;

    ._wz_vehicleMonitoring_cent_left {
      height: 100%;
      width: calc(100% - 220px - 10px);
      float: left;

      .ivu-card-body {
        width: 100%;
        height: calc(100% - 51px);
      }

      ._wz_vehicleMonitoring_cent_left_map {
        width: 100%;
        height: 100%;
        display: flex;
        align-content: space-around;
        flex-direction: column;

      }
    }

    ._wz_vehicleMonitoring_cent_right {
      height: 100%;
      float: right;
      width: 220px;
      box-sizing: border-box;

      .ivu-card-body {
        width: 100%;
        height: calc(100% - 51px);
      }

      ._wz_vehicleMonitoring_cent_right_list {
        width: 100%;
        height: calc(100% - 58px);
        ._wz_vehicleMonitoring_cent_right_listDiv{
          height: calc(100% - 30px);
          overflow: auto;
          width: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
        }

        dl {
          height: calc(100% - 30px);
          overflow: auto;
          width: 100%;

          dd {
            cursor: pointer;
            border-bottom: 1px solid #e6e6e6;
            padding: 10px 5px;
            line-height: 30px;
          }
        }
      }
    }
  }
}
</style>
